package com.arvts.android.project;

import java.util.ArrayList;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.arvts.android.project.adapter.ListViewDataAdapter;
import com.arvts.android.project.adapter.MergeAdapter;
import com.arvts.android.project.data.VehicleDS;
import com.arvts.android.project.model.ContentItem;
import com.arvts.android.project.model.CurrentStatus;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class DashBoardActivity extends Activity implements ActionBar.OnNavigationListener,OnClickListener {

	// Google Map
	private GoogleMap googleMap;
	ArrayList<ContentItem> objects;

	// action bar
    private ActionBar actionBar;
 
    // Refresh menu item
    private MenuItem refreshMenuItem;
    
	public static final String SETTINGS = "SETTINGS";
	SharedPreferences localSP;
	
	public static CurrentStatus status;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
		setContentView(R.layout.fragment_dashboard);
		
		Button bSMS= (Button) findViewById(R.id.button_sms);

		bSMS.setOnClickListener(this);
		
		actionBar = getActionBar();
		
		objects = new ArrayList<ContentItem>();
		
		if(status.getStatus().equals("I")){
			objects.add(new ContentItem("Status", 		":  Idle"));
			objects.add(new ContentItem("Start Time",	":  "+status.getStoped_or_started_time()));
		}
		else if(status.getStatus().equals("M")){
			objects.add(new ContentItem("Status", 		":  Moving"));
			objects.add(new ContentItem("Start Time",	":  "+status.getStoped_or_started_time()));
		}
		else{
			objects.add(new ContentItem("Status", 		":  Stoped"));
			objects.add(new ContentItem("Stop Time ",	":  "+status.getStoped_or_started_time()));
		}
		
		objects.add(new ContentItem("Speed",  		":  "+status.getEcu_speed()+" Km/h"));
		
		
		objects.add(new ContentItem("Running hours",":  "+status.getTIME()));
		
		objects.add(new ContentItem("NB ",			":  Authorized Route"));
		
		ListViewDataAdapter adapter = new ListViewDataAdapter(DashBoardActivity.this, objects);
		
		ListView lv = (ListView) findViewById(R.id.listView1);
	   
	    lv.setAdapter(adapter);

		// map
		try {
			// Loading map
			initilizeMap();

			// Changing map type
			googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

			// Showing / hiding your current location
			googleMap.setMyLocationEnabled(false);

			// Enable / Disable zooming controls
			googleMap.getUiSettings().setZoomControlsEnabled(false);

			// Enable / Disable my location button
			googleMap.getUiSettings().setMyLocationButtonEnabled(true);

			// Enable / Disable Compass icon
			googleMap.getUiSettings().setCompassEnabled(true);

			// Enable / Disable Rotate gesture
			googleMap.getUiSettings().setRotateGesturesEnabled(true);

			// Enable / Disable zooming functionality
			googleMap.getUiSettings().setZoomGesturesEnabled(true);
			
			//SharedPreferences localSP = getSharedPreferences(SETTINGS, Context.MODE_WORLD_READABLE+ Context.MODE_WORLD_WRITEABLE);
			
			double latitude = Double.parseDouble(status.getLatitude());
			double longitude = Double.parseDouble(status.getLongitude());//2.677111, 101.970749

			// lets place some 10 random markers
			// Adding a marker
			MarkerOptions marker = new MarkerOptions().position(
					new LatLng(latitude, longitude)).title(new VehicleDS(this).getVehicleNumberByID(status.getVehicle_id()));

			marker.icon(BitmapDescriptorFactory
					.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));

			googleMap.addMarker(marker);

			// Move the camera to last position with a zoom level
			CameraPosition cameraPosition = new CameraPosition.Builder()
					.target(new LatLng(latitude, longitude)).zoom(15).build();

			googleMap.animateCamera(CameraUpdateFactory
					.newCameraPosition(cameraPosition));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	 @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
			 MenuInflater inflater = getMenuInflater();
		    inflater.inflate(R.menu.main, menu);
		    return super.onCreateOptionsMenu(menu);
		 
	    }
	
	 @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        // Take appropriate action for each action item click
	        switch (item.getItemId()) {
	        
	        case R.id.action_refresh:
	            // refresh
	            refreshMenuItem = item;
	            // load the data from server
	            new SyncData().execute();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	        }
	    }
	
	 
	 /**
	     * Async task to load the data from server
	     * **/
	    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) 
	    private class SyncData extends AsyncTask<String, Void, String> {
	        @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @Override
	        protected void onPreExecute() {
	            // set the progress bar view
	            refreshMenuItem.setActionView(R.layout.action_progressbar);
	 
	            refreshMenuItem.expandActionView();
	        }
	 
	        @Override
	        protected String doInBackground(String... params) {
	            // not making real request in this demo
	            // for now we use a timer to wait for sometime
	            try {
	                Thread.sleep(3000);
	            } catch (InterruptedException e) {
	                e.printStackTrace();
	            }
	            return null;
	        }
	 
	        @Override
	        protected void onPostExecute(String result) {
	            refreshMenuItem.collapseActionView();
	            // remove the progress bar view
	            refreshMenuItem.setActionView(null);
	        }
	    };
	 
	/**
	 * function to load map If map is not created it will create it for you
	 * */
	private void initilizeMap() {
		if (googleMap == null) {
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.map)).getMap();

			// check if map is created successfully or not
			if (googleMap == null) {
				Toast.makeText(DashBoardActivity.this,
						"Sorry! unable to create maps", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}

	/*
	 * creating random postion around a location for testing purpose only
	 */
	private double[] createRandLocation(double latitude, double longitude) {

		return new double[] { latitude + ((Math.random() - 0.5) / 500),
				longitude + ((Math.random() - 0.5) / 500),
				150 + ((Math.random() - 0.5) * 10) };
	}


	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, CommandActivity.class);
		startActivity(intent);
	}


	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		status=null;
	}
	
	
}
